package cn.sanxintong.utils.generate;

import java.io.File;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import cn.sanxintong.entity.ColumnClass;
import cn.sanxintong.entity.constant.Constant;
import cn.sanxintong.entity.constant.FileConstant;
import cn.sanxintong.entity.constant.PackConstant;
import cn.sanxintong.entity.constant.TableConstant;
import cn.sanxintong.utils.common.JdbcTypeConvert;
import cn.sanxintong.utils.common.StrUtils;
import cn.sanxintong.utils.freemarker.FreeMarkerTemplateUtils;

/**
 * 生成mapper.xml 工具类
 * @author hxy
 * @version 1.0.0
 */
public class MapperUtil {
	
	public static void generateMapperFile(ResultSet resultSet,String str) throws Exception{
        final String path = Constant.DISK_PATH + StringUtils.substring(Constant.CHANGE_TABLE_NAME, 3) + FileConstant.MAPPER_PREFIX;
        final String templateName = "Mapper.ftl";
        File mapperFile = new File(path);
        List<ColumnClass> columnClassList = new ArrayList<>();
        ColumnClass columnClass = null;
        System.out.println(resultSet.next());
        while(resultSet.next()){
        	//id字段略过
            if(resultSet.getString(TableConstant.COLUMN_NAME).equals("id")) continue;
            columnClass = new ColumnClass();
            //获取字段名称
            columnClass.setColumnName(resultSet.getString(TableConstant.COLUMN_NAME));
            //获取字段类型
            columnClass.setColumnType(JdbcTypeConvert.mysqlType2JdbcType(resultSet.getString(TableConstant.TYPE_NAME)));
            //转换字段名称，如 sys_name 变成 SysName
            columnClass.setChangeColumnName(StrUtils.replaceUnderLineAndUpperCase(resultSet.getString(TableConstant.COLUMN_NAME)));
            //字段在数据库的注释
            columnClass.setColumnComment(resultSet.getString(TableConstant.REMARKS));
            columnClassList.add(columnClass);
        }
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("primaryKey", str);
        dataMap.put("model_column",columnClassList);
        System.out.println(columnClassList);
        dataMap.put("entityPackage", PackConstant.ENTITY_PACKAGE);
        dataMap.put("daoPackageName", PackConstant.DAO_PACKAGE);
        FreeMarkerTemplateUtils.generateFileByTemplate(templateName,mapperFile,dataMap);
        System.out.println("SQL生成了");
    }
}
